import { toast, clearStorageSync, getStorageSync, setStorageSync } from "../utils/utils.js";
import { API_HOST, API_PROXY, BASE_URL } from "./constant.js";

export const packApiUrl = (url = '') => {
  if (url.slice(0, 4) === 'http') return url
  else return `${API_HOST}${API_PROXY}${url}`
}

export let request = async (url, method, data, loading = true) => {
	let header = {
		'content-type': 'application/x-www-form-urlencoded;charset:utf-8;',
		'cookie': getStorageSync("token") || ''
	};
	
	url = packApiUrl(url);
	
	return new Promise((reslove, reject) => {
		loading && uni.showLoading({
			title: 'loading'
		});
		uni.request({
			url: url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				console.log("res:",res.data);
				uni.hideLoading();
				if (res.errorCode == 0) {
					resovle(res.data);
				} else if (res.errorCode == -1001) {
					toast('登录失效，请重新登录');
					reject(res.data);
					clearStorageSync();
				} else {
					toast('网络连接失败，请稍后重试');
					reject(res.data);
				}
				// 登录后会在cookie中返回账号密码，只要在客户端做cookie持久化存储即可自动登录验证
				if (method == 'POST' && res.header['Set-Cookie']) {
					console.log('cookie:' + res.header['Set-Cookie']);
					setStorageSync('token', res.header['Set-Cookie']);
				}
			},
			fail: (error) => {
				uni.hideLoading();
				toast('网络连接失败，请稍后重试');
				reject(error);
			}
		})
	});
};

// const request = {};

// ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
//   request[method] = (api, data, loading) => baseRequest(api, method, data, loading)
// })

// export request;